import React from 'react';
import BaseComponent from '@/components/BaseComponent';
import styled from 'styled-components';
import { connect } from 'dva';
import styles from './list.less';
import { Button, Card, Col, Input, Popconfirm, Row, Select } from 'antd';
import StandardTable from '@/components/StandardTable';
import CreateView from './create/index';
import EditView from './edit/index';

/**
 * 顶部右侧相关信息
 * @type {StyledComponent<"div", AnyIfEmpty<DefaultTheme>, {}, never>}
 */
const HeaderRight = styled.div`
  display: flex;
  flex-direction: row;
  justify-content: flex-end;
`;

const MBtn = styled.a`
  color: #40a9ff;
  margin-left: 8px;
  margin-right: 8px;
`;

@connect(({ productionwaste, loading }) => ({
  data: productionwaste.data,
  isLoading: loading.effects['productionwaste/listAllByPage'],
  isCreating: loading.effects['productionwaste/create'],
  isUpdating: loading.effects['productionwaste/update'],
  isDeling: loading.effects['productionwaste/deleteById'],
}))
class ProductionwasteList extends BaseComponent {
  constructor(props) {
    super(props);
    this.state = {
      keyword: '',
      selectedRowKeys: [],
      // 新增
      createVisible: false,
      // 预览
      previewVisible: false,
      // 编辑
      updateVisible: false,
      // 产废类别
      rubbishTypes: [],
      // 危险特性
      dangerTypes: [],
      // 待预览或编辑的数据
      record: {},
    };
  }

  columns = [
    {
      title: '废物名称',
      key: 'col2',
      width: 200,
      dataIndex: 'waste_name',
    },
    {
      title: '废物类别',
      key: 'col3',
      width: 200,
      dataIndex: 'waste_type',
    },
    {
      title: '固废代码',
      key: 'col4',
      width: 200,
      dataIndex: 'waste_code',
    },
    {
      title: '危险特性',
      key: 'col5',
      width: 200,
      dataIndex: 'waste_danger_type',
    },
    {
      title: '有害物质名称及含量',
      key: 'col6',
      width: 200,
      dataIndex: 'waste_harmful_matter_content',
    },
    {
      title: '形态',
      key: 'col7',
      width: 200,
      dataIndex: 'waste_form_type',
    },
    {
      title: '主要危险成分',
      key: 'col8',
      width: 200,
      dataIndex: 'waste_hazardous_ingredients',
    },
    {
      title: '包装方式',
      key: 'col9',
      width: 200,
      dataIndex: 'waste_packing',
    },
    {
      title: '应急设备',
      key: 'col10',
      width: 200,
      dataIndex: 'waste_emergency_equipment',
    },
    {
      title: '禁忌措施',
      key: 'col11',
      width: 200,
      dataIndex: 'waste_taboo_measures',
    },
    {
      title: '操作',
      key: 'col16',
      width: 200,
      fixed: 'right',
      render: (text, record, index) => {
        return (
          <div className={styles.operate_col}>
            <MBtn
              onClick={() => {
                this.handlePreviewClick({ record });
              }}
            >
              详情
            </MBtn>
            <MBtn
              onClick={() => {
                this.handleEditClick({ record });
              }}
            >
              编辑
            </MBtn>
            <Popconfirm
              title="确定执行当前操作吗?"
              onConfirm={() => {
                this.handleDelClick({ record });
              }}
            >
              <MBtn>删除</MBtn>
            </Popconfirm>
          </div>
        );
      },
    },
  ];

  componentDidMount() {
    this.listAllByPage();
    this.queryAllDicts();
  }

  /**
   * 分页获取列表数据
   */
  listAllByPage = () => {
    this.listAllByPageBy({});
  };

  listAllByPageBy = params => {
    this.execHttp('productionwaste/listAllByPage', { currentPage: 1, pageSize: 10, ...params });
  };

  /**
   * 获取页面中需要用到的数据字典值
   * @param params
   */
  queryAllDicts = params => {
    this.execHttp('productionwaste/queryAllDicts', {})
      .then(value => {
        console.log(JSON.stringify(value.data));
        const { rubbishTypes, dangerTypes } = value.data;
        this.setState({
          rubbishTypes: rubbishTypes,
          dangerTypes: dangerTypes,
        });
      })
      .catch(reason => console.log(reason));
  };

  /**
   * 执行删除任务
   * @param id
   */
  deleteById = ({ id }) => {
    if (this.props.isDeling) {
      return;
    }
    const hide = this.loadingMessage('操作中,请稍后...');
    this.execHttp('productionwaste/deleteById', { id: id })
      .then(value => {
        hide();
        const {
          success,
          data: { msg },
        } = value;
        if (success) {
          this.successMessage(msg);
        } else {
          this.errorMessage(msg);
        }
        this.listAllByPage();
      })
      .catch(reason => {
        hide();
        this.errorMessage(reason);
      });
  };

  render() {
    const { selectedRowKeys, rubbishTypes, dangerTypes } = this.state;
    const { companyId } = this.props;
    return (
      <div>
        <Card bordered={true} title={''}>
          <Row>
            <Col span={8}>
              <Button
                type="primary"
                style={{ marginRight: '8px' }}
                onClick={this.handleShowCreateClick}
              >
                新建
              </Button>
            </Col>
            <Col span={16}>
              <HeaderRight>
                <Input
                  value={this.state.keyword}
                  style={{ width: '200px', marginRight: '8px' }}
                  placeholder="请输入关键字"
                  allowClear
                  onChange={this.handleKeywordChange}
                />
                <Button
                  type="primary"
                  style={{ marginRight: '8px' }}
                  onClick={this.handleSearchClick}
                >
                  搜索
                </Button>
                <Button type="default" onClick={this.handleResetClick}>
                  重置
                </Button>
              </HeaderRight>
            </Col>
          </Row>
        </Card>{' '}
        {/*列表*/}
        <Card bordered={true} style={{ marginTop: '16px' }}>
          <StandardTable
            data={this.props.data}
            hasSelection={false}
            selectedRows={selectedRowKeys}
            columns={this.columns}
            rowKey={'id'}
            loading={this.props.isLoading}
            onChange={this.handleTableChange}
            scroll={{ x: true }}
          />
        </Card>
        {/*新增*/}
        {this.state.createVisible ? (
          <CreateView
            wrappedComponentRef={createView => (this.createView = createView)}
            visible={this.state.createVisible}
            rubbishTypes={rubbishTypes}
            dangerTypes={dangerTypes}
            companyId={companyId}
            onClose={this.handleCreateViewClose}
            onConfirmClick={this.handleCreateViewConfirmClick}
          ></CreateView>
        ) : null}
        {/*编辑*/}
        {this.state.updateVisible && Object.keys(this.state.record).length > 0 ? (
          <EditView
            wrappedComponentRef={updateView => (this.updateView = updateView)}
            visible={this.state.updateVisible}
            rubbishTypes={rubbishTypes}
            dangerTypes={dangerTypes}
            record={this.state.record}
            onClose={this.handleUpdateViewClose}
            onConfirmClick={this.handleUpdateViewConfirmClick}
          ></EditView>
        ) : null}{' '}
      </div>
    );
  }

  /**
   * 新建按钮被点击
   */
  handleShowCreateClick = () => {
    this.setState({
      createVisible: true,
    });
  };
  /**
   * 关键字改变
   * @param e
   */
  handleKeywordChange = e => {
    const {
      target: { value },
    } = e;
    this.setState({
      keyword: value,
    });
  };
  /**
   *搜索按钮被点击
   */
  handleSearchClick = () => {
    const { keyword } = this.state;
    this.listAllByPageBy({ keyword: keyword });
  };
  /**
   * 重置按钮被点击
   */
  handleResetClick = () => {
    this.setState({ keyword: '' }, () => {
      this.listAllByPageBy({});
    });
  };
  /**
   * table状态改变时调用
   * @param pagination
   * @param filtersArg
   * @param sorter
   */
  handleTableChange = (pagination, filtersArg, sorter) => {
    const params = {
      currentPage: pagination.current,
      pageSize: pagination.pageSize,
    };
    if (sorter.field) {
      params.sorter = `${sorter.field}_${sorter.order}`;
    }
    this.listAllByPageBy(params);
  };
  /**
   *新增关闭按钮被点击
   */
  handleCreateViewClose = e => {
    this.setState({
      createVisible: false,
    });
  };

  /**
   * 新增视图确认按钮被点击
   * @param data
   */
  handleCreateViewConfirmClick = ({ data }) => {
    if (this.props.isCreating) {
      return;
    }
    const hide = this.loadingMessage('操作中,请稍后...');
    this.execHttp('productionwaste/create', { ...data })
      .then(value => {
        hide();
        const {
          success,
          data: { msg },
        } = value;
        if (success) {
          this.successMessage(msg);
        } else {
          this.errorMessage('出错了');
        }
        this.setState({ createVisible: false }, () => {
          this.listAllByPage();
        });
      })
      .catch(reason => {
        hide();
        this.errorMessage(reason);
      });
  };
  /**
   *编辑关闭按钮被点击
   */
  handleUpdateViewClose = e => {
    this.setState({
      updateVisible: false,
    });
  };
  /**
   * 编辑视图确认按钮被点击
   * @param data
   */
  handleUpdateViewConfirmClick = ({ data }) => {
    if (this.props.isUpdating) {
      return;
    }
    const hide = this.loadingMessage('操作中,请稍后...');
    this.execHttp('productionwaste/update', { ...data })
      .then(value => {
        hide();
        const {
          success,
          data: { msg },
        } = value;
        if (success) {
          this.successMessage(msg);
        } else {
          this.errorMessage(msg);
        }
        this.setState({ updateVisible: false }, () => {
          this.listAllByPage();
        });
      })
      .catch(reason => {
        hide();
        this.errorMessage(reason);
      });
  };
  /**
   * 编辑按钮被点击
   * @param record
   */
  handleEditClick = ({ record }) => {
    this.setState({
      record: record,
      updateVisible: true,
    });
  };
  /**
   * 删除按钮被点击
   * @param record
   */
  handleDelClick = ({ record }) => {
    this.deleteById({ id: record.id });
  };
}

export default ProductionwasteList;
